//
//  ClassManagerViewController.m
//  BOSS-SOOC
//
//  Created by apple on 16/8/29.
//  Copyright © 2016年 Gcx. All rights reserved.
//
#define REDCOLOR [self getColor:@"e86666"]

#import "ClassManagerViewController.h"
#import "ClassManagerModel.h"
#import "ClassMamagerCell.h"
#import "SCTableView.h"
#import "EditCourseViewController.h"
#import "SCTypeBtn.h"
#import "NewCoureseViewController.h"
#import "NameListViewController.h"

@interface ClassManagerViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    SCTableView *_myTableView;
    SCTypeBtn   *_succeedBtn;
}
@property (nonatomic, strong) NSMutableArray<ClassManagerModel *> *orders;

@end

@implementation ClassManagerViewController

- (void)viewDidLoad{

    [super viewDidLoad];
    [self setTitle:@"课程管理"];
    
    [self creatTableView];

}

/**
 *  创建列表
 */
- (void)creatTableView{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _myTableView = [[SCTableView alloc]initWithFrame:CGRectMake(0, 64, SIZEWIDTH, SIZEHEIGHT-64 - 55) style:UITableViewStyleGrouped];
    
    _myTableView.backgroundColor = BGC;
    
    _myTableView.separatorColor = colordbdbdb;
    
    _myTableView.delegate = self;
    
    _myTableView.dataSource = self;
    
    _myTableView.showEmpty = YES;
    
    [_myTableView emptyWithTitle:@"暂无订单" image:[UIImage imageNamed:@"空白页-搜索无数据图片"]];
    
    [self.view addSubview:_myTableView];
    
    [self setupRefresh];

    [_myTableView.mj_header beginRefreshing];
    
    _succeedBtn = [[SCTypeBtn alloc]initWithFrame:CGRectMake(0, SIZEHEIGHT-55, SIZEWIDTH, 55)];
    [_succeedBtn setTitle:@"新增课程" forState:UIControlStateNormal];
    _succeedBtn.isCanUse = YES;
    [_succeedBtn addTarget: self action:@ selector(succeedBtnClciked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_succeedBtn];
}

- (void)succeedBtnClciked:(UIButton *)sender{

    NewCoureseViewController *new = [[NewCoureseViewController alloc]init];
    
    new.hidesBottomBarWhenPushed = YES;
    
    [self navigationCanDragBack:YES];
    
    new.myBlock = ^(void){
    
        [_myTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:new animated:YES];
}

#pragma mark -- 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0001;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.orders.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    ClassMamagerCell*cell = [ClassMamagerCell cellWithTab:tableView];
    
    ClassManagerModel *model = self.orders[indexPath.row];
    
    cell.myModel = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    ClassManagerModel *model = self.orders[indexPath.row];
    
    CGRect rect = [self stringRectWithSize:CGSizeMake(SIZEWIDTH -ScaleSize(84), 0) fontSize:42 withString:[NSString stringWithFormat:@"%@  (%@)", model.kcmc, model.skxq]];
    
    return ScaleSize(127) + 20 + rect.size.height;

}
/**
 *  tableView点击事件
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ClassManagerModel *model = self.orders[indexPath.row];
    
    NameListViewController *name = [[NameListViewController alloc]initDataWithClassManagerModel:model];
    
    name.hidesBottomBarWhenPushed = YES;
    
    [self navigationCanDragBack:YES];
    
    [self.navigationController pushViewController:name animated:YES];
}

- (CGRect)stringRectWithSize:(CGSize)size fontSize:(CGFloat)font withString:(NSString *)string
{
    /**
     字符串进行自适应的方法
     
     第一个参数:是进行自适应的尺寸
     第二个参数:样式(模式)
     第三个参数:一些字符串(字体)的属性
     第四个参数:忽略
     */
    CGRect rect =  [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: NormalFont(font)} context:nil];
    
    return  rect;
}

/**
 *  加载数据
 *
 *  @return 是否重置数据
 */
- (void)isReloadData:(BOOL)reload{

    NSInteger pageIndex = 1;
    
    if (reload) {
        
    }else{
        pageIndex = [self sc_currentPageNumWithTotalCount:self.orders.count];
    }
    
    NSDictionary *dic = @{@"oauth_token":@"815bffb68e2ea44e38cf16a98a5a29a4",@"oauth_token_secret":@"8e84bc64f03d73b5c75406ef1d7349f7"};
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    [params setObject:@(10) forKey:@"pageSize"];
    [params setObject:@(pageIndex) forKey:@"pageNo"];
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_courseList params:params];
    
    [self doPOSTConnect:request start:nil success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        
        NSLog(@"resp == %@", resp.originalDictionary);
        
        NSArray<ClassManagerModel*>*newArr = [ClassManagerModel mj_objectArrayWithKeyValuesArray:resp.originalDictionary[@"data"]];
        
        if (reload) {
            
            [self.orders removeAllObjects];
        
        }
        
        [self.orders addObjectsFromArray:newArr];
         
        [_myTableView reloadData];
        
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
        [_myTableView.mj_header endRefreshing];
        [_myTableView.mj_footer endRefreshing];
    }];
}


/**
 *  刷新加载
 */
- (void)setupRefresh{
    
    //    __block __weak OptionTableView *table = self;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [_myTableView.mj_header beginRefreshing];
        
        [self isReloadData:YES];
        
    }];
    header.stateLabel.textColor = COLOR_TITLE_999999;
    header.lastUpdatedTimeLabel.textColor = COLOR_TITLE_999999;
    _myTableView.mj_header = header;
    
    
    MJRefreshAutoNormalFooter * foot = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [_myTableView.mj_footer beginRefreshing];
        
        [self isReloadData:NO];
    }];
    foot.stateLabel.textColor = COLOR_TITLE_999999;
    _myTableView.mj_footer = foot;
    
}

#pragma mark -- 滑动删除和编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return YES;
}

#pragma mark -- ios 9.0
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 添加一个删除按钮
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定删除该课程？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            ClassManagerModel *model = self.orders[indexPath.row];
            
            NSDictionary *dic = @{@"oauth_token":@"815bffb68e2ea44e38cf16a98a5a29a4",@"oauth_token_secret":@"8e84bc64f03d73b5c75406ef1d7349f7"};
            
            NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
            
            [params setObject:model.kcid forKey:@"kcid"];
            
            SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_delCourse params:params];
            
            [self doPOSTConnect:request start:nil success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
                
                NSLog(@"resp == %@", resp.originalDictionary);
                
                if ([resp.originalDictionary[@"status"]integerValue] == 0) {
                    
                    [self.orders removeObjectAtIndex:indexPath.row];
                    
                    [_myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                    
                    if (self.orders.count < 10) {
                        
                        [self isReloadData:YES];
                    }

                } else {
                
                    POST_FAIL(resp.originalDictionary[@"statusCode"]);
                }
                
                
            } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
                
            } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
                
            }];

        }];
        
        [alert addAction:cancel];
        [alert addAction:ok];
        
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }];
    
    // 添加一个更多按钮
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        ClassManagerModel *model = self.orders[indexPath.row];
        
        EditCourseViewController *edit = [[EditCourseViewController alloc]initDataClassManagerModel:model];
        
        [self navigationCanDragBack:YES];
        
        edit.hidesBottomBarWhenPushed = YES;
        
        edit.myBlock = ^(void){
        
            [_myTableView.mj_header beginRefreshing];
        };
        
        [self.navigationController pushViewController:edit animated:YES];
        
    }];
    
    deleteRowAction.backgroundColor = REDCOLOR;
    moreRowAction.backgroundColor = [UIColor lightGrayColor];
    
    return @[deleteRowAction,moreRowAction];
}



- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return @"删除";
}

-(UIColor *)getColor:(NSString *)hexColor {
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}


- (NSInteger)sc_currentPageNumWithTotalCount:(NSInteger)total{
    
    NSInteger pindex = total / 10;
    
    //如果有余数, 则在上方除10的时候把余数丢掉.下方进行判断, 如果有余数, 则+1处理
    if (total % 10) {
        pindex += 1;
    }
    return pindex + 1;
    
}
#pragma mark - GET
-(NSMutableArray<ClassManagerModel *> *)orders{
    if (!_orders) {
        _orders = [[NSMutableArray alloc]init];
    }
    return _orders;
}


@end
